// src/screens/PaypalScreen.js
import React, { useEffect } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Alert } from 'react-native';
import { useSelector } from 'react-redux';
import api from '../services/api';

const PaypalScreen = ({ route, navigation }) => {
  const { orderId } = route.params || {};
  const userInfo = useSelector(state => state.user.userInfo);

  useEffect(() => {
    if (orderId) {
      executePayment();
    } else {
      Alert.alert('错误', '缺少订单信息');
      navigation.goBack();
    }
  }, [orderId]);

  const executePayment = async () => {
    try {
      const response = await api.executePaypalOrder(orderId);
      if (response.success) {
        Alert.alert(
          '支付成功',
          `您已成功充值粉钻！`,
          [
            {
              text: '确定',
              onPress: () => navigation.navigate('Main', { screen: 'Profile' })
            }
          ]
        );
      } else {
        Alert.alert('支付失败', response.message || '支付过程中出现错误');
        navigation.goBack();
      }
    } catch (error) {
      Alert.alert('支付失败', '支付过程中出现错误: ' + error.message);
      navigation.goBack();
    }
  };

  return (
    <View style={styles.container}>
      <ActivityIndicator size="large" color="#0070ba" />
      <Text style={styles.text}>正在处理PayPal支付...</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  text: {
    marginTop: 16,
    fontSize: 16,
    color: '#333',
  },
});

export default PaypalScreen;